package com.yyfax.ph.base;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.View;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.ph.R;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.imageselector.factory.AlbumStorageDirFactory;
import com.yyfax.ph.common.imageselector.factory.BaseAlbumDirFactory;
import com.yyfax.ph.common.imageselector.factory.FroyoAlbumDirFactory;
import com.yyfax.ph.common.imageselector.utils.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * Created by HenryZhang on 2017/2/16.
 * Copyright © 2017 www.yylending.com. All Rights Reserved.
 */
public abstract class PermissionFragment extends BaseFragment implements PermissionsGrantedHelper.PermissionsGrantedListener{
	public static final int REQUEST_CODE_CAMERA = 100;

	protected static final int DEFAULT_PERMISSION_REQUEST_CODE_CAMERA_EXTERNAL_STORAGE = 1;
	protected static final int DEFAULT_PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE = 2;
	protected static final int DEFAULT_PERMISSION_REQUEST_CODE_LOCATION = 3;

	private int mPermissionRequestCodeCameraExternalStorage = DEFAULT_PERMISSION_REQUEST_CODE_CAMERA_EXTERNAL_STORAGE;
	private int mPermissionRequestCodeExternalStorage = DEFAULT_PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE;
	private int mPermissionRequestCodeLocation = DEFAULT_PERMISSION_REQUEST_CODE_LOCATION;

	protected RxPermissions mRxPermissions;
	private DialogBase mDialog;
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;//todo 考虑删掉所有Factory

	@Override
	public void onDestroy() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
		mDialog = null;
		super.onDestroy();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}

		mRxPermissions = new RxPermissions(getActivity());
	}

	protected boolean hasCameraPermission(int requestCode) {
		mPermissionRequestCodeCameraExternalStorage = requestCode;
		boolean hasPermission = false;
		if (PermissionsGrantedHelper.isSdkUnderM()) {
			if (PermissionsGrantedHelper.checkCameraPermission()) {
				hasPermission = true;
			} else {
				hasPermission = false;
			}
		} else {
			if (PermissionsGrantedHelper.hasAllPermission(getActivity(), Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
				hasPermission = true;
			}else {
				hasPermission = false;
				PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, this, requestCode, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
			}		}
		return hasPermission;
	}

	protected boolean hasWriteStoragePermission(int requestCode) {
		mPermissionRequestCodeExternalStorage = requestCode;
		if (PermissionsGrantedHelper.checkAppPermissionWithVersion(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
			return true;
		} else {
			PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, this, requestCode, Manifest.permission.WRITE_EXTERNAL_STORAGE);
			return false;
		}
	}

	protected boolean getLocationPermission(int requestCode) {
		mPermissionRequestCodeLocation = requestCode;
		if (PermissionsGrantedHelper.checkAppPermissionWithVersion(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
			return true;
		} else {
			PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, this, requestCode, Manifest.permission.ACCESS_COARSE_LOCATION);
			return false;
		}
	}

	@Override
	public void permissionsEachGrantedResult(Permission permission) {

	}

	@Override
	public void PermissionsAllGrantedResult(boolean granted, int requestCode) {
		if (requestCode == mPermissionRequestCodeCameraExternalStorage) {
			if (granted) {
				permissionsAllGrantedSuccess(requestCode);
			} else {
				new DialogBase(getActivity(), getString(R.string.camera_permission_not_allowed),
						getString(R.string.camera_permission_not_allowed_content),
						getString(R.string.OK), new DialogBase.BottomOneClickListener() {
					@Override
					public void bottomOneClick(DialogBase dialog) {
						startApplicationDetailSetting();
						dialog.dismiss();
					}
				}).show();
			}
		} else if (requestCode == mPermissionRequestCodeExternalStorage) {
			if (granted) {
				permissionsAllGrantedSuccess(requestCode);
			} else {
				new DialogBase(getActivity(), getString(R.string.no_write_storage_permission),
						getString(R.string.write_permission_not_allowed_content),
						getString(R.string.OK), new DialogBase.BottomOneClickListener() {
					@Override
					public void bottomOneClick(DialogBase dialog) {
						startApplicationDetailSetting();
						dialog.dismiss();
					}
				}).show();
			}
		} else if (requestCode == mPermissionRequestCodeLocation) {
			if (granted) {
				permissionsAllGrantedSuccess(requestCode);
			} else {
				/*new DialogBase(getActivity(), getString(R.string.no_location_permission),
						getString(R.string.location_permission_not_allowed_content),
						getString(R.string.OK), new DialogBase.BottomOneClickListener() {
					@Override
					public void bottomOneClick(DialogBase dialog) {
						startApplicationDetailSetting();
						dialog.dismiss();
					}
				}).show();*/
				permissionsAllGrantedFailure(requestCode);
			}
		}
	}

	protected abstract void permissionsAllGrantedSuccess(int requestCode);
	public void permissionsAllGrantedFailure(int requestCode){}

	private void startApplicationDetailSetting() {
		Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
		startActivity(intent);
	}

	/**
	 * 跳转到系统照相机
	 *
	 * @param authority FileProvider名称
	 * @return 相片的存储路径
	 */
	public String openCamera(String authority) {
		String storagePath = null;
		// 跳转到系统照相机
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
			File f;
			try {
				f = FileUtils.createImageFile(mAlbumStorageDirFactory);
				storagePath = f.getAbsolutePath();
				if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
				} else {
					intent.addFlags(268435456);//可能不需要
					intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					Uri contentUri = FileProvider.getUriForFile(getActivity(), authority, f);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
				}
			} catch (IOException e) {
				storagePath = null;
				e.printStackTrace();
			}
			getActivity().startActivityForResult(intent, REQUEST_CODE_CAMERA);
		} else {
			showToast(R.string.msg_no_camera);
		}
		return storagePath;
	}
}
